package com.guiji.quartz.task;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.guiji.quartz.util.ChromeDriverClonable;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @create: 2021-10-08 11:51
 **/
public class DouyinTask {
	private static final Logger log = LoggerFactory.getLogger(DouyinTask.class);


	public static void mainMethod(ChromeDriverClonable chromeDriver) throws IOException, InterruptedException {
		// 访问榜单页面
		log.info("main================main" + chromeDriver.getCurrentUrl());
		chromeDriver.get("https://creator.douyin.com/creator-micro/billboard/1");
		Thread.sleep(15000L);
		File screenshotFile = ((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE);
		screenshotFile.renameTo(new File("C:\\Users\\Administrator\\Desktop\\douyin\\a.jpg"));

		int k = 2;
		int max = 50;
		while (k < max) {
			//点击小三角下拉框，展出视频
			//*[@id="root"]/div[2]/div[2]/div/div[2]/div/div/div/div/div[1]/div/table/tbody/tr[51]/td[1]/span[1]/svg
			//*[@id="root"]/div[2]/div[2]/div/div[2]/div/div/div/div/div[1]/div/table/tbody/tr[50]/td[1]/span[1]/svg
			if (k > 2) {
				chromeDriver.findElement(By.xpath("//*[@id='root']/div[2]/div[2]/div/div[2]/div/div/div/div/div[1]/div/table/tbody/tr[" + k + "]/td[1]/span[1]")).click();
				Thread.sleep(5000L);
			}

			screenshotFile = ((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE);
			screenshotFile.renameTo(new File("C:\\Users\\Administrator\\Desktop\\douyin\\b" + k + ".jpg"));
			//*[@id="root"]/div[2]/div[2]/div/div[2]/div/div/div/div/div[1]/div/table/tbody/tr[40]/td/div/div/div/div/div[1]/div/div/div[1]/div/img
			//*[@id="root"]/div[2]/div[2]/div/div[2]/div/div/div/div/div[1]/div/table/tbody/tr[40]/td/div/div/div/div/div[9]/div/div/div[1]/div/div/img

			//点击进入页面，并获取第一个url
			List<String> list = new ArrayList<>();
			int y = k + 1;
			if (k == 2) {
				y = 2;
			}
			String url,name;
			try {
				String ss = "//*[@id='root']/div[2]/div[2]/div/div[2]/div/div/div/div/div[1]/div/table/tbody/tr[" + y + "]/td/div/div/div/div/div[1]/div/div/div[1]/div/img";
				chromeDriver.findElement(By.xpath(ss)).click();
				Thread.sleep(2000L);
				WebElement element = chromeDriver.findElement(By.xpath("//video"));
				url = element.getAttribute("src");
				name = chromeDriver.findElement(By.xpath("//div[@class='title--10E2m']")).getText();
			} catch (InterruptedException e) {
				continue;
			}
			list.add(url+"###"+name);
			int i = 2;
			while (true) {
				//点击依次获取第二至到第n个url
				// /html/body/div[4]/div[2]/div/div/div[2]/div/div/div[1]/div[2]
				// /html/body/div[4]/div[2]/div/div/div[5]/div/div/div[1]/div[2]
				try {
					chromeDriver.findElement(By.xpath("//div[@class='slick-track']/div[" + i + "]/div/div/div[1]/div[2]/img")).click();
					Thread.sleep(2000L);
					WebElement element1 = chromeDriver.findElement(By.xpath("//video"));
					list.add(element1.getAttribute("src")+"###"+chromeDriver.findElement(By.xpath("//div[@class='title--10E2m']")).getText());
					i++;
					System.out.println(i);
				} catch (Exception e) {
					break;
				}
			}
			downloadVideo(list);
			chromeDriver.get("https://creator.douyin.com/creator-micro/billboard/1");
			Thread.sleep(15000L);
			k++;
		}

	}

	private static void downloadVideo(List<String> list) {
		ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 25, 20, TimeUnit.SECONDS,
			new ArrayBlockingQueue<>(30), new ThreadPoolExecutor.CallerRunsPolicy());

		for (String url : list) {
			executor.execute(new Runnable() {
				@Override
				public void run() {
					String[] sss = url.split("###");

					System.out.println("=============================" + sss[0]);
					String mp4Path = "D:\\douyinVideo\\" + sss[1] + ".mp4";
					HttpUtil.downloadFile(url, new File(mp4Path), 30000);
				}
			});
		}


	}


	/**
	 * 获取登录的WebDriver
	 */
	public static ChromeDriverClonable getFirefoxDriver() {
		ChromeDriverClonable chromeDriver = null;
		try {
			String osys = System.getProperty("os.name").substring(0, 1);
			String chromedriver = "/usr/bin/chromedriver";
			String chrome = "/opt/google/chrome/chrome";
			if ("w".equalsIgnoreCase(osys)) {
				chromedriver = "C:\\Users\\Administrator\\AppData\\Local\\google\\Chrome\\Application\\chromedriver.exe";
				chrome = "C:\\Users\\Administrator\\AppData\\Local\\google\\Chrome\\Application\\chrome.exe";
			} else {

			}
			System.setProperty("webdriver.chrome.driver", chromedriver);
			System.setProperty("webdriver.chrome.bin", chrome);
			System.setProperty("webdriver.chrome.marionette", chrome);

			ChromeOptions chromeOptions = new ChromeOptions();
			//无页面使用
			chromeOptions.addArguments("--headless");
			//解决DevToolsActivePort文件不存在的报错
			chromeOptions.addArguments("--no-sandbox");
			//指定浏览器分辨率
			chromeOptions.addArguments("window-size=1920x1080");
			//谷歌文档提到需要加上这个属性来规避bug
			chromeOptions.addArguments("--disable-gpu");
			//不加载图片, 提升速度
			//chromeOptions.addArguments("blink-settings=imagesEnabled=false");
			//手动指定使用的浏览器位置
			//chromeOptions.setBinary("/usr/bin/google-chrome");
			chromeDriver = new ChromeDriverClonable(chromeOptions);
			//通过driver控制浏览器打开链接（url）
			chromeDriver.get("https://creator.douyin.com/");
			// 休眠1s,为了让js执行完
			Thread.sleep(1000L);
			//最大化浏览器窗口
			chromeDriver.manage().window().maximize();
			// 页面等待渲染时长，如果你的页面需要动态渲染数据的话一定要留出页面渲染的时间，单位默认是秒
			Wait<WebDriver> wait = new WebDriverWait(chromeDriver, 3);
			//wait.until(ExpectedConditions.presenceOfElementLocated(By.className("chrome-headless")));
			Thread.sleep(1000L);
			File screenshotFile = ((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE);
			screenshotFile.renameTo(new File("C:\\Users\\Administrator\\Desktop\\douyin\\1.jpg"));
			//点击登录按钮
			chromeDriver.findElement(By.xpath("//span[@class='login']")).click();
			Thread.sleep(1000L);
			screenshotFile = ((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE);
			screenshotFile.renameTo(new File("C:\\Users\\Administrator\\Desktop\\douyin\\2.jpg"));
			//点击确认按钮
			chromeDriver.findElement(By.xpath("//span[@class='semi-button-content']")).click();
			Thread.sleep(1000L);
			screenshotFile = ((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE);
			screenshotFile.renameTo(new File("C:\\Users\\Administrator\\Desktop\\douyin\\3.jpg"));
			//点击手机号登录按钮
			chromeDriver.findElement(By.xpath("//*[@id='dialog-0']/div/div[2]/div/div[1]/div[2]")).click();
			Thread.sleep(1000L);
			screenshotFile = ((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE);
			screenshotFile.renameTo(new File("C:\\Users\\Administrator\\Desktop\\douyin\\4.jpg"));
			//点击切换为密码登录按钮
			chromeDriver.findElement(By.xpath("//*[@id='dialog-0']/div/div[2]/div/div[2]/div[2]/div/form/div[3]/span")).click();
			Thread.sleep(1000L);
			screenshotFile = ((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE);
			screenshotFile.renameTo(new File("C:\\Users\\Administrator\\Desktop\\douyin\\5.jpg"));

			chromeDriver.findElement(By.xpath("//input[@type='tel']")).sendKeys(new String[]{"15951678550"});
			chromeDriver.findElement(By.xpath("//input[@type='password']")).sendKeys(new String[]{"Aa755197"});
			chromeDriver.findElement(By.xpath("//*[@id='dialog-0']/div/div[2]/div/div[2]/div[2]/div/form/div[4]/img")).click();
			Thread.sleep(2000L);
			chromeDriver.findElement(By.xpath("//button[@type='submit']")).click();
			Thread.sleep(2000L);
			log.info("mail1111111111111111111111111");

			screenshotFile = ((TakesScreenshot) chromeDriver).getScreenshotAs(OutputType.FILE);
			screenshotFile.renameTo(new File("C:\\Users\\Administrator\\Desktop\\douyin\\6.jpg"));

			return chromeDriver;
		} catch (Exception e) {
			log.info("oh, no Exception");
			e.printStackTrace();
		}
		log.info("mail22222222222222222222222");
		return null;
	}

//	public static void main(String[] args) throws IOException, InterruptedException {
//		mainMethod(getFirefoxDriver());
//	}
}
